package com.tyjc.unique.dlt;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.tyjc.unique.AnaylaseBaseFragment;
import com.tyjc.unique.util.DLT_ZhuShu;
import com.tyjc.unique.view.RandomSetView;
import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.gl.SSQGLResultActivity;
import com.fyzk.activity.lottery.shuzicai.BallInfo;
import com.fyzk.activity.lottery.shuzicai.SelectBallView;
import com.fyzk.activity.lottery.shuzicai.TouZhuHelper;
import com.fyzk.activity.myview.WeiZhi;
import com.tyjc.lottery.R;
import com.fyzk.utils.LotteryIDUtils;
import com.fyzk.utils.RandomUtil;

import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;


/**
 * 双色球过滤类
 *
 * @author miao
 */

@ContentView(R.layout.fg_dltfilter)
public class DltFilterFragment extends AnaylaseBaseFragment implements
        RandomSetView.RandomBtnClickListener, TouZhuHelper.BallItemClickLitener, TouZhuHelper
        .BallClickListener {

    protected SelectBallView redBallView;
    protected SelectBallView blueBallView;

    protected RandomSetView redRandomSet;
    protected RandomSetView blueRandomSet;

    protected List<BallInfo> redBallInfos = new ArrayList<BallInfo>();
    protected List<BallInfo> blueBallInfos = new ArrayList<BallInfo>();

    protected List<List<BallInfo>> arrs = new ArrayList<List<BallInfo>>();

    private TextView mTxt_amount;// 注码彩金
    private RadioGroup mRdg_fs;
    private RadioButton  mRdg_z4b4, mRdg_z4b3, mRdg_z5b4;

    private final int Z4B3 = 3;
    private final int Z4B4 = 2;
    private final int Z5B4 = 1;
    private int type_fs = Z5B4;//

    private String red_code = "";
    private String blue_code = "";

    private ProgressDialog progressdialog;
    @ViewInject(R.id.btn_filter)
    private Button btn_filter;

    private int minRed = 8;

    private int redNum = 35;
    private int blueNum = 12;

    long zhushu;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        redBallView = (SelectBallView) view.findViewById(R.id.redball);
        blueBallView = (SelectBallView) view.findViewById(R.id.blueball);
        initRandomSetView(view);
        initBallList();
        arrs.add(redBallInfos);
        arrs.add(blueBallInfos);
        redBallView.setBallInfoList(redBallInfos);
        blueBallView.setBallInfoList(blueBallInfos);
        initBallViewMax();
        mTxt_amount = (TextView) view.findViewById(R.id.select_amount);
        mRdg_z5b4 = (RadioButton) view.findViewById(R.id.gl_rdb_z5b4);
        mRdg_z4b4 = (RadioButton) view.findViewById(R.id.gl_rdb_z4b4);
        mRdg_z4b3 = (RadioButton) view.findViewById(R.id.gl_rdb_z4b3);
        mRdg_fs = (RadioGroup) view.findViewById(R.id.gl_rdg);
        btn_filter.setOnClickListener(this);

//        play=1：中5保4，个数7-32
//        play=2：中4保4，个数7-32
//        play=3：中4保3，个数7-32

        mRdg_fs.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.gl_rdb_z5b4:// 中5保4
                        type_fs = Z5B4;
                        redRandomSet.setRandomNumRange(7, 32);
                        redBallView.setSelect_max(32);
                        minRed = 7;
                        redRandomSet.setLineTitle("红球（7~32）");
                        break;
                    case R.id.gl_rdb_z4b4:// 中4保4
                        type_fs = Z5B4;
                        redRandomSet.setRandomNumRange(7, 32);
                        redBallView.setSelect_max(32);
                        minRed = 7;
                        redRandomSet.setLineTitle("红球（7~32）");
                        break;
                    case R.id.gl_rdb_z4b3:// 中4保3
                        type_fs = Z5B4;
                        redRandomSet.setRandomNumRange(7, 32);
                        redBallView.setSelect_max(32);
                        minRed = 7;
                        redRandomSet.setLineTitle("红球（7~32）");
                        break;
                    case R.id.gl_rdb_nil:
                        type_fs = 0;
                        break;
                }
            }
        });
        TouZhuHelper.getInstance().setBallItemClickLitener(this);
        TouZhuHelper.getInstance().setBallClickListener(this);
    }


    /**
     * 是否可以过滤
     *
     * @return
     */
    public boolean glAble() {
        return zhushu > 0 && getRedSelectNum() >= minRed;
    }

    private void initCode() {
        StringBuffer red = new StringBuffer();
        StringBuffer blue = new StringBuffer();
        for (int i = 0; i < arrs.get(0).size(); i++) {
            BallInfo info = arrs.get(0).get(i);
            if (info.isSelected()) {
                red.append(info.getNum()).append(",");
            }
        }
        if (red.length() > 1) {
            red.deleteCharAt(red.length() - 1);
            red_code = red.toString();
        }
        for (int i = 0; i < arrs.get(1).size(); i++) {
            BallInfo info = arrs.get(1).get(i);
            if (info.isSelected()) {
                blue.append(info.getNum()).append(",");
            }
        }
        if (blue.length() > 1) {
            blue.deleteCharAt(blue.length() - 1);
            blue_code = blue.toString();
        }
    }

    protected void parserMessage(Message msg) {
        if (progressdialog != null) {
            progressdialog.dismiss();
        }
        switch (msg.what) {
            case 0:
                Intent intent = new Intent(getActivity(), SSQGLResultActivity.class);
                intent.putExtra("result", msg.obj.toString());
                startActivity(intent);
                break;
            case -1:
                AppToast.getToast().show("联网失败");
                break;

            default:
                break;
        }
    }

    public int getRedSelectNum() {
        int selectNum = 0;
        for (BallInfo info : redBallInfos) {
            if (info.isSelected()) {
                selectNum++;
            }
        }
        return selectNum;
    }


    /**
     * 网络连接提示框
     */
    protected ProgressDialog CreateDialog() {
        String waitMessage = "数据处理中……";
        progressdialog = new ProgressDialog(getActivity());
        progressdialog.setMessage(waitMessage);
        progressdialog.setIndeterminate(true);
        progressdialog.setCancelable(true);
        return progressdialog;
    }

    private void requestGL() {

        RequestParams params = new RequestParams("http://123.57.226.31/multiple/rotate/rotate");
        params.addBodyParameter("lotteryType",LotteryIDUtils.DLT_LOTTERY_ID_INT+"");
        params.addBodyParameter("play",type_fs+"");
        params.addBodyParameter("codeValue",red_code);
        params.addBodyParameter("appendcode",blue_code);
        sendRequest(HttpMethod.POST,  params, 1);

    }



    public void initRandomSetView(View view) {
        blueRandomSet = (RandomSetView) view.findViewById(R.id.randomSet_blue);
        redRandomSet = (RandomSetView) view.findViewById(R.id.randomSet_red);
        redRandomSet.setRandomNumRange(7,32);
        blueRandomSet.setRandomNumRange(2,12);
        redRandomSet.setOnRandomBtnClickListener(this);
        blueRandomSet.setOnRandomBtnClickListener(this);
    }

    public void initBallViewMax() {
        redBallView.setSelect_max(32);
    }

    /**
     * 初始化 小球list
     *
     * @param balls
     * @param count 每列显示小球数
     * @param start
     */
    public void initBallList(List<BallInfo> balls, int count, int start,
                             boolean hasZero) {
        balls.clear();
        for (int j = start; j < count + start; j++) {
            BallInfo qiu;
            if (hasZero) {
                if (j < 10) {
                    qiu = new BallInfo("0" + j);
                } else {
                    qiu = new BallInfo("" + j);
                }
            } else {
                qiu = new BallInfo(String.valueOf(j));
            }
            balls.add(qiu);
        }
    }

    public void initBallList() {
        initBallList(redBallInfos, redNum, 1, true);
        initBallList(blueBallInfos, blueNum, 1, true);
    }

    @Override
    public void onRandomBtnClick(RandomSetView v, int randomCount) {
        switch (v.getId()) {
            case R.id.randomSet_red:
                int redArr[] = RandomUtil.randomNoRepeat(randomCount, 0, redNum);
                initBallList(redBallInfos, redNum, 1, true);
                for (int i = 0; i < redArr.length; i++) {
                    redBallInfos.get(redArr[i]).setSelected(true);
                }
                redBallView.invalidate();
                break;
            case R.id.randomSet_blue:
                int blueArr[] = RandomUtil.randomNoRepeat(randomCount, 0, blueNum);
                initBallList(blueBallInfos, blueNum, 1, true);
                for (int i = 0; i < blueArr.length; i++) {
                    blueBallInfos.get(blueArr[i]).setSelected(true);
                }
                blueBallView.invalidate();
                break;

            default:
                break;
        }
        ballClick(null);
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void showData() {
        super.showData();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onClick(View arg0) {
        super.onClick(arg0);
        if (glAble()) {
            initCode();
            CreateDialog().show();
            requestGL();
        } else {
            AppToast.getToast().show("红球个数至少为8个，篮球至少选择1个！");
        }

    }

    @Override
    public void ballClick(WeiZhi wz) {
        zhushu = new DLT_ZhuShu().betZhuShu(arrs);
        mTxt_amount.setText("总计，" + zhushu + "注 " + zhushu * 2 + "米");
    }

    @Override
    public void ballClick() {
        ballClick(null);
    }
}
